<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class ArticleController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Response|void
     * @throws ValidationException
     */
    public function index(Request $request, $category_id)
    {
    	$input = $request->input();
    	$input['page'] = isset ($input['page'])?$input['page']:'1';
    	$input['limit'] = isset ($input['limit'])?$input['limit']:'15';
    	$input['language'] = isset ($input['language'])?$input['language']:'0';

    	$article_ids = [];

    	if(in_array($category_id,['3','4'])){
            $uid = $request->user()->id;

            $article_ids = Db::table('article_user')
                ->where('user_id','=',$uid)
                ->pluck('article_id')->toArray();

            $article_lists = Db::table('article')
                ->where('menu_article_id','=',$category_id)
                ->where(function ($query) use($input) {
                    $query->where('language', $input['language']);
                })
                ->whereIn('id',$article_ids)
                ->paginate($input['limit'],['*'],'page',$input['page'])
                ->toArray();
        }else{
            $article_lists = Db::table('article')
                ->where('menu_article_id','=',$category_id)
                ->where(function ($query) use($input) {
                    $query->where('language', $input['language']);
                })
                ->paginate($input['limit'],['*'],'page',$input['page'])
                ->toArray();
        }

        foreach ($article_lists['data'] as $key => $value) {
            $value->image = asset(Storage::url($value->image));
        }  
        
    	return response()->json(['code'=>'1','data'=>$article_lists]);
    }


    public function info(Request $request, $article_id){
        $result = Db::table('article')->where('id','=',$article_id)->first();
        $result->image = asset(Storage::url($result->image));

        if(empty($result->id))return response()->json(['message' => 'id非法参数','code'=>'-1']);

        return response()->json(['code'=>'1','data'=>$result]);
    }
}
